package com.lagou.edu.service.impl;

import com.lagou.edu.pojo.Order;
import com.lagou.edu.repository.OrderRepository;
import com.lagou.edu.service.OrderMessage;
import com.lagou.edu.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author stevejson
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMessage orderMessage;

    @Autowired
    private OrderRepository orderRepository;

    @Override
    public Boolean createOrder(Integer orderId, String name) {
        // 发送mq
        Boolean success = orderMessage.publisherCreateOrder(orderId);
        if (!success) {
            return false;
        }
        // 创建数据库
        Order order = new Order();
        order.setOrderId(orderId);
        order.setVersion(0);
        order.setState(Order.STATE.CREATE);
        order.setName(name);
        orderRepository.save(order);
        return true;
    }

    @Override
    public Boolean cancelOrder(Integer id) {
        Order order = orderRepository.findFirstByOrderId(id);
        if (null == order) {
            return false;
        }
        if(!Order.STATE.CREATE.equals(order.getState())){
            return false;
        }
        Integer integer = orderRepository.updateOrderState(order.getVersion(), order.getOrderId(), Order.STATE.CANCEL.ordinal());
        return integer == 1;
    }

    @Override
    public Boolean payOrder(Integer id) {
        Order order = orderRepository.findFirstByOrderId(id);
        if (null == order) {
            return false;
        }
        if(!Order.STATE.CREATE.equals(order.getState())){
            return false;
        }
        Integer integer = orderRepository.updateOrderState(order.getVersion(), order.getOrderId(), Order.STATE.PAYED.ordinal());
        return integer == 1;
    }
}
